package logic;

import java.io.File;
import java.util.AbstractMap.SimpleEntry;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import qw.easyFrame.throwables.DefinedRuntimeException;
import qw.easyFrame.tools.TextFinder;
import qw.easyFrame.tools.statics.StringUtil;
import qw.easyFrame.view.EasyTextArea;
import view.MainFrame;

/**
 * .主逻辑.
 * @author Rex
 *
 */
public class Searcher {
	
	/**
	 * 标记程序是否正在运行.
	 */
	private static volatile boolean running = false;

	public synchronized static void run(File[] chosen, JComboBox<String> box, JTextField target, JTextField formats,
			EasyTextArea area, JCheckBox check) {
		if (running) {
			area.append("程序正在运行，请勿重复点击！");
		} else {
			area.append("开始搜索，请稍候……");
			running = true;
			new Thread(() -> act(chosen, box, target, formats, area, check)).start();
		}
	}
	
	private static void act(File[] chosen, JComboBox<String> box, JTextField target, JTextField formats,
			EasyTextArea area, JCheckBox check) {
		String msg = "搜索已完成！";
		try {
			File file = null;
			if (chosen == null || chosen.length == 0 || (file = chosen[0]) == null) {
				throw new DefinedRuntimeException(false, "您未选择任何文件或文件夹！");
			}
			
			String charset = box.getSelectedItem().toString();
			if (MainFrame.box_text.equals(charset)) {
				charset = "UTF-8";
			}
			
			String targerText = target.getText().trim();
			if (targerText.isEmpty() || MainFrame.field0_text.equals(targerText)) {
				throw new DefinedRuntimeException(false, "您未输入要搜索的文字！");
			}
			
			String[] format = { ".txt", ".html", ".xml", ".htm" };
			String text = formats.getText().trim();
			if (MainFrame.field1_text.equals(text) == false && text.isEmpty() == false) {
				format = StringUtil.split(text, " ");
			}
			
			// 是否忽略大小写
			Object[] select = check.getSelectedObjects();
			boolean ignoreCase = select != null;
			
			TextFinder finder = new TextFinder();
			finder.setDir(file);
			finder.setCharset(charset);
			finder.setTarget(targerText, ignoreCase);
			finder.setExtensions(format);
			
			List<SimpleEntry<File,Integer>> find = finder.find();
			if (find ==null || find.size()==0) {
				throw new DefinedRuntimeException(false, "未搜索到结果！");
			}
			
			for (SimpleEntry<File, Integer> e : find) {
				area.append(e.getKey().getAbsolutePath() + " 第" + e.getValue() + "行");
			}
		} catch (DefinedRuntimeException e) {
			msg = e.getMessage();
		} catch (Exception e) {
			msg = "程序运行时出现未知的异常！";
		} finally {
			running = false;
			area.append(msg);
		}
	}
	
}